<template>
  <div class="category-manager wap">
    <x-header v-if="!this.$fromApp(this)" :left-options="{backText: ''}"><span>商品分类</span>
      <div class="overwrite-title-right" slot="right" @click="addCategory">新增分类</div>
    </x-header>

    <div class="main">
      <draggable
        :list="categoryList"
        class="list-group"
        ghost-class="ghost"
        :move="checkMove"
        @start="dragging = true"
        @end="dragging = false"
        v-if="!isOpenGoods"
      >
        <div class="item vux-1px-b" v-for="(item,index) in categoryList" :key="item.id">
          <!--<div  @touchstart="showDeleteButton(item,index)" @touchend="clearLoop(item)" class="header display-flex justify-content-flex-justify align-items-center">-->
          <div class="header display-flex justify-content-flex-justify align-items-center">
            <div class="flex-1 beyond-one" @click="showDeleteButton(item,index)">
              <span class="customer-type-name">{{item.name}}</span>
            </div>
            <div>
              <span class="add-customer" @click="addCustomer(item)">新增商品 <x-icon size="20" type="ios-plus-empty"
                                                                                 class="icon-gray"></x-icon></span>

              <span class="expand" @click="expandList(item,index)">
            {{item.expand?'收起':'展开'}}
            <x-icon size="15" v-if="item.expand" type="ios-arrow-up" class="icon-blue"></x-icon>
            <x-icon size="15" v-if="!item.expand" type="ios-arrow-down" class="icon-blue"></x-icon>
          </span>
            </div>
          </div>
          <goodMangerItem
            @dialogComfrim="moveDialogComfrim" :checkListArray="checkListArray" :useType="2" v-if="item.expand"
            :list="item.goodsList"></goodMangerItem>
          <div v-if="item.expand&&item.goodsList&&item.goodsList.length>=5" @click="showMore(item)"
               class="more display-flex justify-content-flex-center align-items-center"><span>进入分类,查看更多</span>
            <x-icon type="ios-arrow-right" size="15"></x-icon>
          </div>
        </div>
      </draggable>
      <!--<no-data v-show="loadOk" @refreshData="refresh(0)" :list="categoryList"></no-data>-->

      <scroller
        ref="scroll"
        v-if="isOpenGoods"
      >
        <div>
          <div class="item vux-1px-b" v-for="(item,index) in categoryList" :key="item.id">
            <!--<div  @touchstart="showDeleteButton(item,index)" @touchend="clearLoop(item)" class="header display-flex justify-content-flex-justify align-items-center">-->
            <div class="header display-flex justify-content-flex-justify align-items-center">
              <div class="flex-1 beyond-one" @click="showDeleteButton(item,index)">
                <span class="customer-type-name">{{item.name}}</span>
              </div>
              <div>
                <span class="add-customer" @click="addCustomer(item)">新增商品 <x-icon size="20" type="ios-plus-empty"
                                                                                   class="icon-gray"></x-icon></span>

                <span class="expand" @click="expandList(item,index)">
                  {{item.expand?'收起':'展开'}}
                  <x-icon size="15" v-if="item.expand" type="ios-arrow-up" class="icon-blue"></x-icon>
                  <x-icon size="15" v-if="!item.expand" type="ios-arrow-down" class="icon-blue"></x-icon>
                </span>
              </div>
            </div>
            <goodMangerItem
              @dialogComfrim="moveDialogComfrim" :checkListArray="checkListArray" :useType="2" v-if="item.expand"
              :list="item.goodsList"></goodMangerItem>
            <div v-if="item.expand&&item.goodsList&&item.goodsList.length>=5" @click="showMore(item)"
                 class="more display-flex justify-content-flex-center align-items-center"><span>进入分类,查看更多</span>
              <x-icon type="ios-arrow-right" size="15"></x-icon>
            </div>
          </div>
        </div>
        <no-data v-show="loadOk" @refreshData="refresh(0)" :list="categoryList"></no-data>
      </scroller>


    </div>


    <div v-transfer-dom>
      <x-dialog v-model="dialog" :hide-on-blur="true">
        <div class="category-dialog">
          <div class="category-title" v-if="dialogType==0">新增分类:</div>
          <div class="category-title" v-if="dialogType==1">修改分类:</div>
          <input maxlength="20" v-model="categoryName" class="category-input normal-input" placeholder="请输入分类名称"
                 type="text">

        </div>
        <div class="btn-comfirm-container" v-if="dialogType==0">
          <div class="btn-comfirm align-items-center display-flex justify-content-flex-center" @click="closeDialog">
            <span>确定</span></div>
        </div>

        <div class="btn-comfirm-container category-dialog-bottom" v-if="dialogType==1">
          <!--<div>删除分类</div>-->
          <!--<div>保存</div>-->
          <div class="btn-del-category align-items-center display-flex justify-content-flex-center"
               @click="delCategory"><span>删除分类</span></div>
          <div class="btn-save-categroy align-items-center display-flex justify-content-flex-center"
               @click="updateCategory"><span>保存</span></div>
        </div>
      </x-dialog>
    </div>
  </div>
</template>
<script>

  import goodMangerItem from '../../components/good-manager-item.vue'
  import draggable from "vuedraggable"

  export default {
    components: {
      goodMangerItem,
      draggable
    },
    data() {
      return {
        dialog: false,
        categoryList: [],
        lastSelectIndex: {index: -1, id: ''},
        checkListArray: [],
        categoryName: "",
        token: "",
        loadOk: false,
        dialogType: 0,  //0新增分类；1：修改分类
        categoryInfo: '',//修改时临时代替
        isOpenGoods: false,
        promise:null
      }
    },
    created() {
      this.initData();
    },
    beforeDestroy() {
      console.log("-----beforeDestroy", this.categoryList)
      //离开的时候提交排序接口

    },
    mounted() {
      window['androidCallJs'] = this.androidCallJs;
    },
    methods: {
      checkMove: function (e) {
        window.console.log("Future index: " + e.draggedContext.futureIndex);

        if(this.promise){
          clearTimeout(this.promise);
        }
        this.promise=setTimeout(()=>{
          let idList = []
          for (let i = 0; i < this.categoryList.length; i++) {
            idList.push(this.categoryList[i].id);
          }
          this.$ajax.post("goods/category/sort", {idList: idList.join(',')}, (res) => {
          })
          this.promise=null;
        },3000)
      },
      androidCallJs(val) {
        let obj = this.$getJson(val);
        if (obj.code == 1002) {
          this.addCategory();
        }
      },
      refresh() {
        this.initData(0);
      },
      initData(type) {
        this.$ajax.get("goods/category/list", (res) => {
          type == 0 && this.$refs.scroll && this.$refs.scroll.finishPullToRefresh();
          if (res.code == 200) {
            this.categoryList = res.data;
            console.log(this.categoryList)
            if (this.categoryList && this.categoryList.length > 0) {
              this.checkListArray = [];
              for (let i = 0; i < this.categoryList.length; i++) {
                this.checkListArray.push({key: this.categoryList[i].id, value: this.categoryList[i].name});
                if (this.categoryList[i].id == this.lastSelectIndex.id) {
                  this.categoryList[i].expand = true;
                } else {
                  this.categoryList[i].expand = false;
                }
              }
              if (this.lastSelectIndex.index > this.categoryList.length) {
                this.lastSelectIndex.index = -1;
              }
            }
          } else {
            this.$vux.toast.text(res.msg, 'center');
          }
          this.loadOk = true;
        }, {})
      },
      addCategory() {
        this.dialogType = 0;
        this.dialog = true;
        this.categoryName = "";
      },
      addCustomer(item) {
        if (this.$fromApp(this)) {
          this.$callJava({title: item.name, id: item.id, code: 1004})
        }
      },
      checkChange() {

      },
      closeDialog() {
        if (this.categoryName.trim().length == 0) {
          this.$vux.toast.text('请输入正确的分类', 'center');
          return;
        }

        this.dialog = false;
        if (this.categoryName != '') {
          this.$ajax.post("goods/category/create", {categoryName: this.categoryName}, (res) => {
            if (res.code == 200) {
              this.$vux.toast.text('新增成功', 'center');
              this.initData();
            } else {
              this.$vux.toast.text(res.msg, 'center');
            }
          })
        }
      },
      moveDialogComfrim() {
        this.initData();
      },
      showMore(item) {
        if (this.$fromApp(this)) {
          this.$callJava({
            url: this.$webUrl + "good/zone?from=app&id=" + item.id + "&name=" + encodeURIComponent(item.name.toString().replace(/%/g, '~~pct~~')) + "&Authorization=" + this.$storage.get("token"),
            title: item.name
          })
        } else {
          this.$router.push({path: '/good/zone', query: {id: item.id, title: item.name}})
        }
      },
      expandList(item, index) {
        console.log(item)
        if (this.lastSelectIndex.index == -1) {
          this.lastSelectIndex.index = index;
          this.lastSelectIndex.id = item.id;
          item.expand = !item.expand;
          this.isOpenGoods=item.expand;
          this.$set(this.categoryList, this.lastSelectIndex.index, item)
        } else {
          if (this.lastSelectIndex.index != index) {
            this.categoryList[this.lastSelectIndex.index].expand = false;
            this.$set(this.categoryList, this.lastSelectIndex.index, this.categoryList[this.lastSelectIndex.index])
            item.expand = !item.expand;
            this.isOpenGoods=item.expand;
            this.lastSelectIndex.index = index;
            this.lastSelectIndex.id = item.id;
            this.$set(this.categoryList, index, item)
          } else {
            this.lastSelectIndex.index = index;
            this.lastSelectIndex.id = item.id;
            item.expand = !item.expand;
            this.isOpenGoods=item.expand;
            this.$set(this.categoryList, this.lastSelectIndex.index, item)
          }
        }
        console.log(this.categoryList)
      },
      delCategory() {
        this.dialog = false;
        let _this = this;
        setTimeout(() => {
          _this.$vux.confirm.show({
            title: '确定要删除吗',
            value: false,
            "showInput": false,
            onCancel: () => {

            },
            onConfirm: (e) => {
              _this.$ajax.get("goods/category/delete", (res2) => {
                console.log(res2)
                if (res2.code == 200) {
                  _this.$vux.toast.text('删除成功', 'center');
                  for (var i = 0; i < _this.categoryList.length; i++) {
                    if (_this.categoryList[i].id == _this.categoryInfo.id) {
                      _this.categoryList.splice(i, 1)
                    }
                  }
                  // item.name=e;
                  // this.$set(this.categoryList,index,item)
                } else {
                  _this.$vux.toast.text(res2.msg, 'center');
                }
              }, {categoryId: _this.categoryInfo.id})
            }
          })
        }, 500)
      },
      updateCategory() {
        this.dialog = false;
        this.$ajax.post("goods/category/update", {
          categoryId: this.categoryInfo.id,
          categoryName: this.categoryName
        }, (res) => {
          if (res.code == 200) {
            this.$vux.toast.text('修改成功', 'center');
            for (let i = 0; i < this.categoryList.length; i++) {
              if (this.categoryList[i].id == this.categoryInfo.id) {
                this.categoryList[i].name = this.categoryName;
              }
            }
            // item.name=e;
            // this.$set(this.categoryList,index,item)
          } else {
            this.$vux.toast.text(res.msg, 'center');
          }
        })
      },
      showDeleteButton(item, index) {
        console.log("======item", item);
        this.dialogType = 1;
        this.dialog = true;
        this.categoryName = item.name;
        this.categoryInfo = item;
        // this.$vux.confirm.setInputValue(item.name);
        // clearTimeout(this.loop);
        // const _this=this;
        // console.log(this.$vux.confirm)
        // // this.loop = setTimeout(() => {
        //   this.$vux.confirm.show({
        //     title: '修改分类',
        //     value: true,
        //     "showInput": true,
        //     "inputAttrs":{
        //       maxlength:20
        //     },
        //     // showCancelButton:false,
        //     cancelText:'删除',
        //     onShow(){
        //       _this.$vux.confirm.setInputValue(item.name);
        //     },
        //
        //     onCancel: () => {
        //       setTimeout(()=>{
        //         _this.$vux.confirm.show({
        //           title: '确定要删除吗',
        //           value: true,
        //           "showInput": false,
        //           "inputAttrs":{
        //             maxlength:20
        //           },
        //           onShow(){
        //             _this.$vux.confirm.setInputValue(item.name);
        //           },
        //           onCancel: () => {
        //
        //           },
        //           onConfirm: (e) => {
        //             _this.$ajax.get("goods/category/delete",(res2)=>{
        //               console.log(res2)
        //               if(res2.code==200){
        //                 _this.$vux.toast.text('删除成功', 'center');
        //                 for(var i=0;i<_this.categoryList.length;i++){
        //                   if(_this.categoryList[i].id==item.id){
        //                     _this.categoryList.splice(i,1)
        //                   }
        //                 }
        //                 // item.name=e;
        //                 // this.$set(this.categoryList,index,item)
        //               }else{
        //                 _this.$vux.toast.text(res2.msg, 'center');
        //               }
        //             },{categoryId:item.id})
        //           }
        //         })
        //       },500)
        //
        //     },
        //     onConfirm: (e) => {
        //       this.$ajax.post("goods/category/update",{categoryId:item.id,categoryName:e},(res)=>{
        //         if(res.code==200){
        //           this.$vux.toast.text('修改成功', 'center');
        //           item.name=e;
        //           this.$set(this.categoryList,index,item)
        //         }else{
        //           this.$vux.toast.text(res.msg, 'center');
        //         }
        //       })
        //     }
        //   })
        // // }, 1000);
      },
      clearLoop(item) {
        clearTimeout(this.loop);
      }
    }
  }
</script>

<style lang="less" type="text/less" scoped>


  .category-manager {
    background: #fff;

    .overwrite-title-right {
      color: #fff;
      font-size: 0.32rem;
    }

    .item {
      padding: 0.45rem 0rem 0 0rem;

      /deep/ .weui-cells {
        margin-top: 0rem !important;
      }

      /deep/ .weui-cell {
        padding: 0rem !important;
      }

      /deep/ .weui-input {
        border: 1px solid #ddd;
        padding: 0.1rem;
        border-radius: 0.1rem;
        font-size: .24rem;
        text-align: center;
        box-sizing: border-box;
        height: .6rem;
      }

      .add-category {
        background: #527DD9;
        border-radius: 0.06rem;
        color: #fff;
        padding: 0.02rem 0.08rem;
        font-size: .28rem;
        margin: 0rem 0.1rem 0 .2rem;
      }

      .header {
        padding: 0 .3rem 0 .3rem;
        padding-bottom: .36rem;
      }

      .customer-type-name {
        font-size: .34rem;
        font-weight: bold;
      }

      .add-customer {
        margin-right: .2rem;
      }

      .add-customer, .expand {
        height: .64rem;
        border: 1px solid #ddd;
        border-radius: .32rem;
        padding: .1rem .15rem .1rem .2rem;
      }

      .icon-gray, .icon-blue {
        fill: #999;
        vertical-align: middle;
        margin-top: -0.03rem;
      }

      .icon-blue {
        fill: #527DD9;
      }
    }

    .more {
      padding: .2rem;

      span {
        color: #999;
        font-size: .24rem;
        margin-right: .1rem;
      }

      svg {
        fill: #ddd
      }
    }
  }

  /deep/ .weui-dialog {
    border-radius: 0.1rem;
  }

  .category-dialog {
    overflow: scroll;
    padding-left: 0.4rem;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    text-align: left;

    /deep/ .weui-cell__bd p {
      text-align: left;
      padding-left: 0.4rem;
      font-size: 0.34rem;
      color: #333;
    }

    /deep/ .weui-cells_checkbox .weui-check:checked + .vux-checklist-icon-checked:before {
      color: #FF3B47;
    }

    /deep/ .weui-cells:before, /deep/ .weui-cell:before, /deep/ .weui-cells:after {
      border: none;
    }
  }

  .category-dialog-bottom {
    display: flex;
    flex-direction: row;
    justify-content: center;
    font-size: .34rem;
  }

  .btn-del-category {
    flex: 1;
    color: #fff;
    background-color: #8E919F;
    margin: 0 0rem .4rem .5rem;
    border-radius: .42rem;
    padding: .14rem;
    /*height:.84rem;*/
  }

  .btn-save-categroy {
    flex: 1;
    color: #fff;
    margin: 0 .5rem .4rem .5rem;
    background: rgba(82, 125, 217, 1);
    border-radius: .42rem;
    /*height:.84rem;*/
  }

  /deep/ .weui-cell {
    font-size: .3rem;
    border-radius: .1rem;
    border: 1px solid #ddd;
    margin-right: .56rem;
    margin-left: .26rem;
  }

  .category-title {
    font-size: 0.34rem;
    font-weight: bold;
    text-align: left;
  }

  .btn-comfirm {
    font-size: .34rem;
    font-weight: 500;
    color: #fff;
    height: .84rem;
    background: rgba(82, 125, 217, 1);
    border-radius: .42rem;
    margin: 0 .5rem .4rem .5rem;
  }

  .category-input {
    text-align: left;
    padding-right: .1rem;
    outline: none;
    padding-left: .28rem;
    margin-top: .3rem;
    height: .8rem;
    width: 85%;
    border-radius: .05rem;
    border: 1px solid #ddd;
  }

  .category-input::-webkit-input-placeholder {
    color: #bbb;
  }

</style>
